<?php

header('Content-Type: application/json');

/ 上传配置
$uploadDir = 'uploads/';  // 上传目录
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']; // 允许的文件类型
$maxSize = 5 * 1024 * 1024; // 最大5MB

// 创建上传目录
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// 检查文件是否上传成功
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['error' => '文件上传失败']);
    exit;
}

$file = $_FILES['file'];

// 验证文件类型
if (!in_array($file['type'], $allowedTypes)) {
    http_response_code(415);
    echo json_encode(['error' => '不支持的文件类型']);
    exit;
}

// 验证文件大小
if ($file['size'] > $maxSize) {
    http_response_code(413);
    echo json_encode(['error' => '文件超过5MB限制']);
    exit;
}

// 生成安全文件名
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$safeFilename = uniqid() . '_' . substr(md5($file['name']), 0, 8) . '.' . $extension;

// 移动文件到上传目录
if (move_uploaded_file($file['tmp_name'], $uploadDir . $safeFilename)) {
    echo json_encode([
        'filename' => $safeFilename,
        'originalname' => $file['name'],
        'size' => $file['size'],
        'path' => $uploadDir . $safeFilename
    ]);
} else {
    http_response_code(500);
    echo json_encode(['error' => '文件保存失败']);
}










?>